package com.woniu.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MqConfig {
    // 业务交换机（接收延迟消息）
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange("delay.exchange");
    }

    // 死信交换机（消息过期后转发到实际消费队列）
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange("deadLetter.exchange");
    }

    // 延迟队列（设置x-dead-letter-exchange和x-message-ttl）
    @Bean
    public Queue delayQueue() {
        Map<String, Object> args = new HashMap<>();
        // 设置死信交换机
        args.put("x-dead-letter-exchange", "deadLetter.exchange");
        // 设置死信路由键（决定消息过期后转发到哪个队列）
        args.put("x-dead-letter-routing-key", "delay");
        // 设置固定TTL
        //args.put("x-message-ttl", 15000);
        return new Queue("delay.queue", true, false, false, args);
    }

    // 实际消费队列（最终消费者监听此队列）
    @Bean
    public Queue realQueue() {
        return new Queue("real.queue");
    }

    // 绑定延迟队列到业务交换机
    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay");
    }

    // 绑定实际队列到死信交换机
    @Bean
    public Binding realBinding() {
        return BindingBuilder.bind(realQueue()).to(deadLetterExchange()).with("delay");
    }

    /**
     * 配置消息转换器
     * @return
     */
    @Bean
    public MessageConverter Jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
